#!/usr/bin/perl
#
# Do weird stuff with an sql database
# In this case: Take incoming email and store it into a database
# of machine registrations.
#

# tricks to locate the lib in source dir
use FindBin;
use POSIX;
use lib "$FindBin::Bin";

use Mach;

# Logging nonsense
if (! -t STDERR) {
    open(STDERR, ">>$FindBin::Bin/../logs/machine-update-log")
	|| die "Unable to open logfile";
}

if ($ARGV[0] eq "-d") {
    shift;
    $Mach::DEBUG = 1;
}

# Lock file. Needed to avoid computer meltdown at times...

$EX_TEMPFAIL = 75;
#$lockprefix = "email/mailerdir"; # permission trouble
$lockprefix = "/tmp";
$channel = int(rand() * 4);
$lockfile = "countmach.LOCK$channel";
$waitcount = 0;
while (!sysopen(HANDLE, "$lockprefix/$lockfile", O_CREAT|O_EXCL|O_RDWR, 0744)) {
    ++ $waitcount;
    if ($waitcount > 10) {
        
        print STDERR ">>>>machines/countmail exiting because of timeout on channel $channel\n";
        $! = $EX_TEMPFAIL;
        exit($EX_TEMPFAIL);
    }
    $0 = "countmachines($waitcount) waiting for lock-$channel";
    print STDERR "Sysopen failed: $!\n" if $MACH::DEBUG;
    sleep 10;
}
close HANDLE;

# Go through STDIN

$messagecount = 0;

while (<>) {
    if (/^From /) {
#	if ($sender =~ /lonnie\@lanell.launi.com/) {
#	    warn "Another dupe from lonnie\@lanell.launi.com";
#	} else {
	    eval 'Mach::processmessage($message)';
#	}
	warn $@ if $@;
	$message = '';
	++ $messagecount;
	$sender = $';
	warn "Starting msg from $'\n";
    }
    $message .= $_;
}
#if ($sender =~ /root\@l2.ries.local/) {
#    warn "Another dupe from root\@l2.ries.local\n";
#} else {
    eval 'Mach::processmessage($message)';
#}
warn $@ if $@;

if (-t STDERR) {
    warn "$messagecount messages processed\n";
}

unlink "$lockprefix/$lockfile";



	
	


